package cn.xutongxue.book_sales.controller;


import cn.xutongxue.book_sales.base.Errors;
import cn.xutongxue.book_sales.base.Result;
import cn.xutongxue.book_sales.entity.User;
import cn.xutongxue.book_sales.mapper.UserMapper;
import cn.xutongxue.book_sales.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author XuTongXue
 * @since 2021-12-02
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;


    @PostMapping("/register")
    public Result register(@RequestBody User user) {

        User user1 = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (!StringUtils.isEmpty(user1))
            return Result.fail(701,"账号已存在,请重新注册!");
        else {
            user.setStatus(1);
            System.out.println(user);
            userService.save(user);
            if(user.getUserId() != null) {
                return Result.ok("注册成功",null);
            }
        }

        return Result.fail(Errors.UNKNOWN_ERROR);
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .eq("username",user.getUsername())
                .eq("pw_md5", user.getPwMd5());

        User user1 = userService.getOne(wrapper);
        if(ObjectUtils.isEmpty(user1)) {
            return Result.fail(702, "账号或密码错误");
        } else if(user1.getStatus() == 0) {
            return Result.fail(703, "账号被禁用！请联系管理员!");
        } else {
            return Result.ok("登录成功", userService.getOne(wrapper));
        }

    }

    @PostMapping("/delUser")
    public Result delUser(@RequestBody User user) {
        if(userService.removeById(user.getUserId()))
            return Result.ok("删除成功", null);
        return Result.fail(704, "删除失败!");
    }

    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user) {

        if(userService.updateById(user))
            return Result.ok("修改成功", null);

        return Result.fail(705, "修改失败");

    }

    @GetMapping("/get")
    public Result getAllUser() {
        List<User> list = userService.list();
        return Result.ok(list);
    }

}
